package com.shiliao.app.update;

import android.content.Context;
import android.content.Intent;

import com.shiliao.app.update.dowload.SilentConfig;
import com.shiliao.app.update.dowload.SilentDownloadService;
import com.yimei.framework.YimeiFrameworkAppliction;
import com.yimei.framework.util.LogUtil;
import com.yimei.framework.util.StringUtils;

/**
 * 版本更新管理
 * Created by yjl on 2017/7/24.
 */
public class UpateManager {
    public static final String ACTION_DOWLOAD_APP = "dowload_app";//下载app标志

    private UpateManager() {

    }


    /**
     * 开始下载
     *
     * @param context
     * @param url
     * @param fileName
     */
    public static void startDowload(Context context, String url, String fileName, String conditon) {
        startDowload(context, url, fileName, conditon, null);
    }

    /**
     * 开始启动下载service,下载app
     *
     * @param context
     * @param url      //下载url
     * @param fileName //文件名
     * @param md5      //文件md5值目前不必须
     */
    public static void startDowload(Context context, String url, String fileName, String condition, String md5) {
        Intent serviceIntent = new Intent();
        serviceIntent.setClass(context, SilentDownloadService.class);
        serviceIntent.putExtra(SilentConfig.CALLBACK_ACTION_NAME, ACTION_DOWLOAD_APP);
        serviceIntent.putExtra(SilentConfig.CALLBACK_EXTRA_NAME, md5);
        serviceIntent.putExtra(SilentConfig.DOWNLOAD_URL_NAME, url);
        serviceIntent.putExtra(SilentConfig.DOWNLOAD_FILE_NAME, fileName);
        serviceIntent.putExtra(SilentConfig.CALLBACK_DOANLOAD_CONDITION, condition);
        context.startService(serviceIntent);
    }

    /**
     * 下载更新
     *
     * @param updateEntity //下载的entity
     * @param userChoice   //用户选择是否下载
     */
    public static void startDowload(UpdateEntity updateEntity, boolean userChoice) {
        String[] names = updateEntity.url.split("\\/");
        String name = names[names.length - 1];
        LogUtil.e("yjl", "下载URL：" + updateEntity.url);
        if (!StringUtils.isEmpty(name)) {
            String condition = SilentConfig.DOWNLOAD_CONDITION_WIFI;
            if (updateEntity.forceUpdate == 1 || userChoice) {
                condition = SilentConfig.DOWNLOAD_CONDITION_CONNECTION;//强制更新
            }
            startDowload(YimeiFrameworkAppliction.getInstance(), updateEntity.url, name, condition);
        }
    }
}
